package com.smartfast4j.common.component.fileManager.controller;

import com.smartfast4j.common.bean.R;
import com.smartfast4j.common.component.fileManager.bean.UploadResult;
import com.smartfast4j.common.component.fileManager.service.FileService;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/fileManager")
public class FileServiceController {

    //日志打印
    private static final Logger logger = LoggerFactory.getLogger(FileServiceController.class);

    @Autowired
    private FileService fileService;

    /**
     * 上传单个文件（测试通过）
     *
     * @return
     */
    @RequestMapping("/uploadFile")
    public R uploadFile(@RequestParam(value = "file", required = false) MultipartFile file) {
        logger.info("上传单个文件入口:"+file.getName());
        UploadResult uploadResult = fileService.uploadFile(file);
        return R.ok(uploadResult);
    }


    /**
     * 上传多文件(测试通过)
     *
     * @return
     */
    @RequestMapping("/uploadFiles")
    public R uploadFiles(HttpServletRequest request) {
        Map<String, Object> dataMap = new HashMap<>();
        CommonsMultipartResolver mReso = new CommonsMultipartResolver(request.getServletContext());
        if (mReso.isMultipart(request)) {
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) request;
            //获取上传文件
            List<MultipartFile> multipartFiles = mreq.getFiles("files");
            //移除multipartFiles集合中文件size等于0的那些文件
            multipartFiles.removeIf(tmpFile -> tmpFile.getSize() == 0);

            List<MultipartFile> multipartFileList = new ArrayList<>();
            for (MultipartFile multipartFile : multipartFiles) {
                try {
                    multipartFileList.add(multipartFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //保存上传文件
            List<UploadResult> uploadFileList = fileService.uploadFile(multipartFileList);
            dataMap.put("list", uploadFileList);
        }
        return R.ok(dataMap);
    }

    /**
     * 上传网络文件
     *
     * @param fileUrl 文件URL
     * @return FileUploadResult 文件上传结果
     */
    @RequestMapping("/uploadNetworkFile")
    public R uploadNetworkFile(String fileUrl) {
        UploadResult fileUploadResult = new UploadResult();
        try {
            UploadResult uploadResult = fileService.uploadNetworkFile(fileUrl);
            BeanUtils.copyProperties(fileUploadResult, uploadResult);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            fileUploadResult.setIsUploadSuccess(false);
        }
        return R.ok(fileUploadResult);
    }

    /**
     * 上传网络文件
     *
     * @param fileUrl 文件URL
     * @param fileExt 文件后缀
     * @return FileUploadResult 文件上传结果
     */
    @RequestMapping("/uploadNetworkFile2")
    public R uploadNetworkFile2(String fileUrl, String fileExt) {
        UploadResult fileUploadResult = new UploadResult();
        try {
            UploadResult uploadResult = fileService.uploadNetworkFile(fileUrl, fileExt);
            BeanUtils.copyProperties(fileUploadResult, uploadResult);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            fileUploadResult.setIsUploadSuccess(false);
        }
        return R.ok(fileUploadResult);
    }

    /**
     * 上传文件输入流
     *
     * @param inputStream 文件输入流
     * @param fileName    原始文件名(带后缀,如1.png,2.jpg)
     * @return FileUploadResult 文件上传结果
     */
    @RequestMapping("/uploadFileInputStream")
    public R uploadFile(@RequestBody InputStream inputStream, @RequestParam("fileName") String fileName) {
        UploadResult fileUploadResult = new UploadResult();
        try {
            UploadResult uploadResult = fileService.uploadFile(inputStream, fileName);
            BeanUtils.copyProperties(fileUploadResult, uploadResult);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            fileUploadResult.setIsUploadSuccess(false);
        }
        return R.ok(fileUploadResult);
    }

    /**
     * 上传文件到文件服务器
     * @param file
     * @return
     */
    @RequestMapping("/uploadFile2FileServer")
    public R uploadFile2FileServer(File file){
        UploadResult fileUploadResult = new UploadResult();
        try {
            UploadResult uploadResult = fileService.uploadFile(file,"");
            BeanUtils.copyProperties(fileUploadResult,uploadResult);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            fileUploadResult.setIsUploadSuccess(false);
        }
        return R.ok(fileUploadResult);
    }

    /**
     * 批量删除文件
     * @param lstFileSavePath
     * @return
     */
    @RequestMapping("/batchDeleteFile")
    public R batchDeleteFile(@RequestParam List<String> lstFileSavePath){
        String fileSavePath = lstFileSavePath.get(0);
        //截取文件保存目录，所有的文件都保存在同一个目录下
        String directory = fileSavePath.substring(0,fileSavePath.lastIndexOf("/"));
        List<String> fileNames = new ArrayList<>();
        for(String filePath:lstFileSavePath){
            //截取文件名
            String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
            fileNames.add(fileName);
        }
        logger.debug("directory:"+directory);
        Map<String,Integer> resultMap = fileService.batchDeleteFile(directory,fileNames);
        return R.ok(resultMap);
    }

    /**
     * 下载文件
     * @param response
     * @param fileUrl
     * @param fileName
     * @return
     */
    @RequestMapping("/downFile")
    public R downFile(HttpServletResponse response, HttpServletRequest request,String fileUrl, String fileName){
        logger.info("获取传递过来文件下载文件名："+fileName);
        String userAgent = request.getHeader("User-Agent");
        // 针对IE或者以IE为内核的浏览器：
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            try {
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage(),e);
            }
        } else {
            // 非IE浏览器的处理：
            try {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage(),e);
            }
        }
        logger.info("转码后文件下载文件名："+fileName);
        fileService.downFile(response,fileUrl,fileName);
        return null;
    }
}
